package com.hfdg.process.ctrl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hfdg.process.model.ProcessModel;
import com.hfdg.process.model.TaskModel;
import com.hfdg.process.service.ProcessDataService;
import com.hfdg.process.service.TaskDataService;
import com.hfdg.prototype.base.model.AjaxResult;
import org.bson.codecs.IdGenerator;
import org.flowable.engine.*;
import org.flowable.engine.impl.cmd.AddMultiInstanceExecutionCmd;
import org.flowable.engine.impl.cmd.CreateTaskCmd;
import org.flowable.engine.impl.persistence.entity.CommentEntity;
import org.flowable.engine.impl.persistence.entity.CommentEntityImpl;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.task.Comment;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskBuilder;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
//import org.springframework.session.SessionRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName TaskCtrl
 * @Description TODO
 * @Author yuelh
 * @Date 2020-2-3 22:25
 * @Version 1.0
 * @Company 会飞的锅工作室
 **/
@Controller
@RequestMapping("/task")
public class TaskCtrl {
    @Autowired
    RepositoryService repositoryService;
    @Autowired
    RuntimeService runtimeService;
    @Autowired
    FormService formService;
    @Autowired
    TaskService taskService;
    @Autowired
    ProcessDataService processDataService;
    @Autowired
    ManagementService managementService;
    @Autowired
    HistoryService historyService;

    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    TaskDataService taskDataService;
//    @Autowired
//    SessionRepository sessionRepository;




    @RequestMapping("/toProcessView")
    public String toProcessView(String taskId, Model model){
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult();
        if(null!=task.getExecutionId()){
            model.addAttribute("fragment","processDefault");
        }else{
            model.addAttribute("fragment","processCounterSign");
        }
        model.addAttribute("taskId",taskId);
        model.addAttribute("processName",processDefinition.getName());
        Map<String,Object> params = new HashMap<>();
        params.put("processInstanceId",task.getProcessInstanceId());
        model.addAttribute("processHistoryList",taskDataService.listProcessComment(params));
        return "commons/process/form/"+processDefinition.getKey();
    }

    @RequestMapping("/toHandleView/{view}")
    public String toHandleView(@PathVariable String view,String taskId, Model model){
        model.addAttribute("taskId",taskId);
        return "commons/process/handle/"+view;
    }

    @RequestMapping("/to/{type}ListView")
    public String toListView(@PathVariable String type){
        return "commons/process/"+type+"ListView";
    }

    @RequestMapping("/getPagingTodo")
    @ResponseBody
    public AjaxResult getPagingTaskToDo(int offset, int limit, String orderBy, Map<String, Object> params, HttpServletRequest request){
        params.put("assignee",request.getSession().getAttribute("uid"));
        return  AjaxResult.success(taskDataService.listToDo(offset,limit,orderBy,params));
    }
    @RequestMapping("/getPagingDone")
    @ResponseBody
    public AjaxResult getPagingDone(int offset, int limit, String orderBy, Map<String, Object> params,HttpServletRequest request){
        params.put("assignee",request.getSession().getAttribute("uid"));
        return  AjaxResult.success(taskDataService.listDone(offset,limit,orderBy,params));
    }
    @RequestMapping("/submit")
    @ResponseBody
    public AjaxResult submit(String taskId,String processHandleData){
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        JSONObject processHandleMap=JSONObject.parseObject(processHandleData);
        taskService.addComment(taskId,task.getProcessInstanceId(),"流转",processHandleMap.get("opinion")+"");
        taskService.complete(taskId,processHandleMap);
        return AjaxResult.success();
    }
    @RequestMapping("/reject")
    @ResponseBody
    public AjaxResult reject(String taskId,String opinion){
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        taskService.addComment(taskId,task.getProcessInstanceId(),"驳回",opinion);
        taskService.complete(taskId);
        runtimeService.deleteProcessInstance(task.getProcessInstanceId(),opinion);
        return AjaxResult.success();
    }

    @RequestMapping("/counterSignSubmit")
    @ResponseBody
    public AjaxResult countSignSubmit(String taskId,String opinion){
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        taskService.addComment(taskId,task.getProcessInstanceId(),"会签办理",opinion);
        taskService.complete(taskId);
        return AjaxResult.success();
    }

    @RequestMapping("/endProcess")
    @ResponseBody
    public AjaxResult endProcess(String taskId,String opinion){
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        taskService.addComment(taskId,task.getProcessInstanceId(),"办结",opinion);
        taskService.complete(taskId);
        runtimeService.deleteProcessInstance(task.getProcessInstanceId(),opinion);
        return AjaxResult.success();
    }
    @RequestMapping("/addSign")
    @ResponseBody
    public AjaxResult addSign(String taskId,String processHandleData){
        JSONObject processHandleMap=JSONObject.parseObject(processHandleData);
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        JSONArray jsonArray = JSONArray.parseArray(processHandleMap.getString("signUser"));
        for(int i=0;i<jsonArray.size();i++){
            Map<String,Object> handler=new HashMap<>();
            handler.put("nextHandler",jsonArray.get(i));
            TaskBuilder taskBuilder = taskService.createTaskBuilder();
            TaskEntity taskEntity = (TaskEntity) taskService.newTask(UUID.randomUUID().toString().replaceAll("-",""));
            taskEntity.setAssignee(jsonArray.get(i)+"");
            taskEntity.setName(task.getName()+"-会签");
            taskEntity.setAssignee(jsonArray.get(i)+"");
            taskEntity.setCategory("会签");
            taskEntity.setFormKey(task.getFormKey());
            taskEntity.setCategory(task.getCategory());
            taskEntity.setProcessInstanceId(task.getProcessInstanceId());
            taskEntity.setProcessDefinitionId(task.getProcessDefinitionId());
            taskService.saveTask(taskEntity);

//
//            AddMultiInstanceExecutionCmd addMultiInstanceExecutionCmd= new AddMultiInstanceExecutionCmd(task.getTaskDefinitionKey(),task.getProcessInstanceId(),handler);
//            managementService.executeCommand(addMultiInstanceExecutionCmd);
        }
        return AjaxResult.success();
    }
    @RequestMapping("/to/CreateView")
    public String toCreateView(){
        return "commons/task/taskCreateView";
    }
    @RequestMapping("/to/taskCreatedListView")
    public String toCreatedTaskListView(){
        return  "commons/task/taskCreatedListView";
    }

    @RequestMapping("/createTask")
    @ResponseBody
    public AjaxResult createTask(TaskModel taskModel){
        TaskBuilder taskBuilder = taskService.createTaskBuilder();
        taskBuilder.name(taskModel.getTaskName());
        taskBuilder.assignee(taskModel.getAssigneeUid());
        taskBuilder.owner(taskModel.getOwnerUid());
        taskBuilder.description(taskModel.getTaskDescription());
        taskBuilder.category(taskBuilder.getCategory());
        taskBuilder.dueDate(new Date());
        taskBuilder.create();
        return AjaxResult.success();
    }
    @RequestMapping("/createSubTask")
    @ResponseBody
    public AjaxResult createSubTask(TaskModel taskModel,String parentTaskId){
        TaskBuilder taskBuilder = taskService.createTaskBuilder();
        taskBuilder.name(taskModel.getTaskName());
        taskBuilder.assignee(taskModel.getAssigneeUid());
        taskBuilder.owner(taskModel.getOwnerUid());
        taskBuilder.description(taskModel.getTaskDescription());
        taskBuilder.category(taskBuilder.getCategory());
        taskBuilder.dueDate(new Date());
        taskBuilder.parentTaskId(parentTaskId);
        taskBuilder.create();
        return AjaxResult.success();
    }


}
